﻿using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace StudentInfoSystem.UI.Views
{
    public partial class SplashScreenWindow : Window
    {
        // 添加公共事件
        public event Action? CardAnimationCompleted;

        // 添加动画完成标志
        private bool _particleAnimationCompleted;
        private bool _cardAnimationCompleted;

        // 修改动画时间常量
        private const int CardDurationMs = 1200; // 延长卡片动画

        private const int ParticleCount = 100; // 增加到100个粒子
        private readonly List<Ellipse> _particles = new();
        private readonly Random _random = new();

        private readonly DoubleAnimation _progressAnimation = new()
        {
            Duration = TimeSpan.FromMilliseconds(500),
            EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut }
        };

        public SplashScreenWindow()
        {
            InitializeComponent();
            // 设置启动画面居中
            WindowStartupLocation = WindowStartupLocation.CenterScreen;

            // 重置状态
            _particleAnimationCompleted = false;
            _cardAnimationCompleted = false;

            // 初始隐藏卡片和进度条（重要！）
            Card.Opacity = 0;
            ProgressTrack.Opacity = 0;

            InitializeParticles();
        }
        private void InitializeParticles()
        {
            // 预定义几种更饱和的颜色
            Color[] colors = {
        Color.FromArgb(230, 3, 218, 198),   // 饱和青色
        Color.FromArgb(220, 187, 134, 252),  // 饱和紫色
        Color.FromArgb(200, 79, 109, 245),   // 饱和蓝色
        Color.FromArgb(240, 255, 107, 107)  // 添加暖色调粒子
    };

            for (int i = 0; i < ParticleCount; i++)
            {
                // 随机选择颜色
                Color color = colors[_random.Next(colors.Length)];

                // 增加粒子大小范围(3-12像素)
                int size = _random.Next(3, 13);
                bool isLargeParticle = _random.NextDouble() > 0.8; // 20%的大粒子

                var ellipse = new Ellipse
                {
                    Width = size,
                    Height = size,
                    Opacity = 0,
                    RenderTransform = new ScaleTransform(),
                    Fill = new RadialGradientBrush
                    {
                        GradientStops =
                {
                    new GradientStop(Color.FromArgb(255, color.R, color.G, color.B), 0),
                    new GradientStop(color, 0.5),
                    new GradientStop(Color.FromArgb(100, color.R, color.G, color.B), 1)
                }
                    },
                    Effect = new BlurEffect { Radius = isLargeParticle ? 5 : 2 } // 大粒子添加更多模糊
                };

                ParticleContainer.Items.Add(ellipse);
                _particles.Add(ellipse);
            }
        }

        public void StartParticleConvergence()
        {
            const int spreadRadius = 170;
            var centerX = Width / 2;
            var centerY = Height / 2;

            foreach (var particle in _particles)
            {
                // 增加粒子分布密度（中心区域粒子更多）
                double angle = _random.NextDouble() * Math.PI * 2;
                double distance = _random.NextDouble() * spreadRadius;

                double startX = centerX + Math.Cos(angle) * distance;
                double startY = centerY + Math.Sin(angle) * distance;

                Canvas.SetLeft(particle, startX);
                Canvas.SetTop(particle, startY);
                particle.Opacity = 1;

                var storyboard = new Storyboard();

                // X轴移动 - 增加速度变化
                double duration = _random.Next(600, 1000);
                var moveX = new DoubleAnimation(startX, centerX,
                    TimeSpan.FromMilliseconds(duration))
                {
                    EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut }
                };

                // Y轴移动 - 与X轴不同时长创造更自然效果
                var moveY = new DoubleAnimation(startY, centerY,
                    TimeSpan.FromMilliseconds(duration * _random.NextDouble() + 300))
                {
                    EasingFunction = new CircleEase { EasingMode = EasingMode.EaseIn }
                };

                // 淡入淡出效果 - 增加透明度变化幅度
                var fade = new DoubleAnimationUsingKeyFrames();
                fade.KeyFrames.Add(new LinearDoubleKeyFrame(0, KeyTime.FromTimeSpan(TimeSpan.Zero)));
                fade.KeyFrames.Add(new LinearDoubleKeyFrame(1, KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(200))));
                fade.KeyFrames.Add(new LinearDoubleKeyFrame(1, KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(600))));
                fade.KeyFrames.Add(new LinearDoubleKeyFrame(0, KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(800))));

                // 缩放效果 - 粒子汇聚时缩小
                double scaleEnd = _random.NextDouble() * 0.3 + 0.1;
                var scaleX = new DoubleAnimation(1, scaleEnd,
                    TimeSpan.FromMilliseconds(duration));
                var scaleY = new DoubleAnimation(1, scaleEnd,
                    TimeSpan.FromMilliseconds(duration));

                // 添加颜色强化动画（汇聚过程中变亮）
                var colorAnim = new ColorAnimation(
                    ((RadialGradientBrush)particle.Fill).GradientStops[0].Color,
                    Colors.White,
                    TimeSpan.FromMilliseconds(duration / 2));

                colorAnim.AutoReverse = true;
                colorAnim.RepeatBehavior = new RepeatBehavior(2);

                // 添加到故事板
                storyboard.Children.Add(moveX);
                storyboard.Children.Add(moveY);
                storyboard.Children.Add(fade);
                storyboard.Children.Add(scaleX);
                storyboard.Children.Add(scaleY);
                storyboard.Children.Add(colorAnim);

                Storyboard.SetTarget(moveX, particle);
                Storyboard.SetTarget(moveY, particle);
                Storyboard.SetTarget(fade, particle);
                Storyboard.SetTarget(scaleX, particle.RenderTransform);
                Storyboard.SetTarget(scaleY, particle.RenderTransform);
                Storyboard.SetTarget(colorAnim, ((RadialGradientBrush)particle.Fill).GradientStops[0]);

                Storyboard.SetTargetProperty(moveX, new PropertyPath(Canvas.LeftProperty));
                Storyboard.SetTargetProperty(moveY, new PropertyPath(Canvas.TopProperty));
                Storyboard.SetTargetProperty(fade, new PropertyPath(OpacityProperty));
                Storyboard.SetTargetProperty(scaleX, new PropertyPath(ScaleTransform.ScaleXProperty));
                Storyboard.SetTargetProperty(scaleY, new PropertyPath(ScaleTransform.ScaleYProperty));
                Storyboard.SetTargetProperty(colorAnim, new PropertyPath(GradientStop.ColorProperty));

                // 随机延迟启动
                storyboard.BeginTime = TimeSpan.FromMilliseconds(_random.Next(0, 400));
                storyboard.Begin();
            }
        }

        public void StartCardFormation()
        {
            // 确保卡片在动画前可见
            Card.Opacity = 1;

            // 关键修复：设置变换中心为卡片中心
            Card.RenderTransformOrigin = new Point(0.5, 0.5);

            // 初始状态：卡片尺寸为0（从中心缩放）
            Card.RenderTransform = new ScaleTransform(0.08, 0.08);

            // 缩放动画（从0到1）
            var scaleAnimation = new DoubleAnimation(0.08, 1, TimeSpan.FromMilliseconds(CardDurationMs))
            {
                EasingFunction = new ElasticEase { Oscillations = 2, Springiness = 6 }
            };

            scaleAnimation.Completed += (s, e) => {
                ProgressTrack.Opacity = 1;
                _cardAnimationCompleted = true;
                CardAnimationCompleted?.Invoke();
            };

            // 同时执行淡入和缩放
            var fadeIn = new DoubleAnimation(0, 1, TimeSpan.FromMilliseconds(CardDurationMs));
            Card.BeginAnimation(OpacityProperty, fadeIn);
            Card.RenderTransform.BeginAnimation(ScaleTransform.ScaleXProperty, scaleAnimation);
            Card.RenderTransform.BeginAnimation(ScaleTransform.ScaleYProperty, scaleAnimation);

            // 启动Logo光晕动画
            StartLogoGlowAnimation();
        }

        // Logo光晕动画
        private void StartLogoGlowAnimation()
        {
            // 获取光晕层
            var glowLayer = FindName("GlowLayer") as Border;
            var glowBlur = FindName("GlowBlur") as BlurEffect;
            if (glowLayer == null || glowBlur == null) return;

            // 创建光晕背景动画（蓝紫渐变）
            var colorAnimation = new ColorAnimation
            {
                From = Colors.Transparent,
                To = Color.FromArgb(150, 138, 43, 226), // 半透明紫色
                Duration = TimeSpan.FromSeconds(1),
                AutoReverse = true,
                RepeatBehavior = RepeatBehavior.Forever,
                EasingFunction = new SineEase()
            };

            // 创建模糊半径动画（脉动效果）
            var blurAnimation = new DoubleAnimation
            {
                From = 0,
                To = 25,
                Duration = TimeSpan.FromSeconds(1.2),
                AutoReverse = true,
                RepeatBehavior = RepeatBehavior.Forever
            };

            // 创建不透明度动画（增强效果）
            var opacityAnimation = new DoubleAnimation
            {
                From = 0.3,
                To = 0.8,
                Duration = TimeSpan.FromSeconds(1.5),
                AutoReverse = true,
                RepeatBehavior = RepeatBehavior.Forever
            };

            // 设置光晕背景
            var brush = new SolidColorBrush();
            glowLayer.Background = brush;

            // 启动动画
            glowLayer.BeginAnimation(OpacityProperty, opacityAnimation);
            brush.BeginAnimation(SolidColorBrush.ColorProperty, colorAnimation);
            glowBlur.BeginAnimation(BlurEffect.RadiusProperty, blurAnimation);
        }

        public void UpdateProgress(double value, string message = "")
        {
            // 更新进度条宽度（0-300范围）
            var progressWidth = value * 3;
            _progressAnimation.To = progressWidth;
            ProgressText.Text = $"{value:0}%"; // 更新百分比
            StatusTextBlock.Text = message;
            // 添加光效位置同步
            Canvas.SetLeft(GlowEffect, value * 300 - 10);
            ProgressTrack.BeginAnimation(WidthProperty, _progressAnimation);
        }

        private void SetParticlePosition(Ellipse particle, double x, double y)
        {
            Canvas.SetLeft(particle, x);
            Canvas.SetTop(particle, y);
        }
    }
}